#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>

int arry[100]; 
//父子进程会发生写时拷贝
pid_t backup(const char* file)
{
    pid_t id = fork();
    if(id == 0 )
    {
        //子进程完成备份保存
        FILE* fp = fopen(file, "w");
        for(int i = 0; i < 100; i++)
        {
            fprintf(fp, "%d ", arry[i]);
        }
        
        fclose(fp);
        exit(0);    
    }
    return id;
}

int main()
{
    srand(time(NULL)^getpid());
    //父进程数据
    int i = 0;
    //将每一轮数据保存，并且是每一轮都同时进行，并发进行
    for(i = 0; i < 100; i++)
    {
        arry[i] = rand() % 10;
    }
    pid_t ret1 = backup("test1.txt");
    
    for(i = 0; i < 100; i++)
    {
        arry[i] = rand() % 10;
   
    }
    pid_t ret2 = backup("test2.txt");
    
    for(i = 0; i < 100; i++)
    {
        arry[i] = rand() % 10;
    }
    pid_t ret3 = backup("test3.txt");
    
    for(i = 0; i < 100; i++)
    {
        arry[i] = rand() % 10;
    }
    pid_t ret4 = backup("test4.txt");
    
    return 0;
}
